<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>知识库AI助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36BFFA',
                        accent: '#7B61FF',
                        neutral: '#1D2939',
                        'neutral-light': '#F9FAFB',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-all-300 {
                transition: all 0.3s ease;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-neutral min-h-screen flex flex-col">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-robot text-primary text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold text-primary">知识库AI助手</h1>
            </div>
            <div class="flex items-center space-x-4">
                <button id="clearSessionBtn" class="text-neutral hover:text-primary transition-all-300 flex items-center">
                    <i class="fa fa-refresh mr-1"></i>
                    <span class="hidden sm:inline">清除会话</span>
                </button>
            </div>
        </div>
    </header>

    <main class="flex-grow container mx-auto px-4 py-8 max-w-5xl">
        <!-- 上传区域 -->
        <section class="bg-white rounded-xl shadow-md p-6 mb-8 transform hover:shadow-lg transition-all-300">
            <h2 class="text-lg md:text-xl font-semibold mb-4 flex items-center">
                <i class="fa fa-cloud-upload text-primary mr-2"></i>
                上传知识库文件
            </h2>
            <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-primary transition-all-300">
                <input type="file" id="fileInput" class="hidden" multiple>
                <label for="fileInput" class="cursor-pointer">
                    <i class="fa fa-file-text-o text-4xl text-gray-400 mb-3 block"></i>
                    <p class="text-gray-500 mb-2">点击或拖拽文件到这里上传</p>
                    <p class="text-sm text-gray-400">支持 PDF、Word、文本等格式</p>
                </label>
                <div id="selectedFiles" class="mt-4 flex flex-wrap gap-2"></div>
            </div>
            <div class="mt-4 flex justify-between">
                <button onclick="uploadFile()" id="uploadBtn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg flex items-center transition-all-300 disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fa fa-upload mr-2"></i>
                    上传文件
                </button>
                <span id="uploadStatus" class="text-sm text-gray-500"></span>
            </div>
        </section>

        <!-- 提问区域 -->
        <section class="bg-white rounded-xl shadow-md p-6 mb-8 transform hover:shadow-lg transition-all-300">
            <h2 class="text-lg md:text-xl font-semibold mb-4 flex items-center">
                <i class="fa fa-question-circle text-primary mr-2"></i>
                提问
            </h2>
            <div class="relative">
                <textarea id="userInput" placeholder="请输入你的问题..." class="w-full p-4 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300 resize-none" rows="4"></textarea>
                <div class="absolute right-3 bottom-3 text-xs text-gray-400">
                    <span id="charCount">0</span>/500
                </div>
            </div>
            <div class="mt-4 flex justify-between items-center">
                <button onclick="generateContent()" id="generateBtn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg flex items-center transition-all-300 disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fa fa-magic mr-2"></i>
                    生成回答
                </button>
                <div id="sessionStatus" class="text-sm flex items-center">
                    <i class="fa fa-circle-o text-gray-400 mr-1"></i>
                    <span>未上传文件</span>
                </div>
            </div>
        </section>

        <!-- 结果区域 -->
        <section id="resultSection" class="bg-white rounded-xl shadow-md p-6 transform hover:shadow-lg transition-all-300 hidden">
            <h2 class="text-lg md:text-xl font-semibold mb-4 flex items-center">
                <i class="fa fa-comments-o text-primary mr-2"></i>
                回答结果
            </h2>
            <div id="result" class="prose max-w-none"></div>
            <div class="mt-4 flex justify-end">
                <button onclick="clearResult()" class="text-gray-600 hover:text-primary transition-all-300 flex items-center">
                    <i class="fa fa-trash-o mr-1"></i>
                    清除结果
                </button>
            </div>
        </section>

        <!-- 加载中状态 -->
        <div id="loadingOverlay" class="fixed inset-0 bg-black/30 flex items-center justify-center z-50 hidden">
            <div class="bg-white p-6 rounded-lg shadow-lg flex flex-col items-center">
                <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mb-3"></div>
                <p id="loadingText">处理中...</p>
            </div>
        </div>
    </main>

    <footer class="bg-neutral text-white py-6 mt-auto">
        <div class="container mx-auto px-4 text-center">
            <p>© 2025 知识库AI助手 - 为您的知识需求提供智能支持</p>
            <p class="text-sm mt-2 text-gray-400">基于ROS与Web技术的智慧农业巡检机器人管理系统</p>
        </div>
    </footer>

    <script>
        // 监听文件选择
        document.getElementById('fileInput').addEventListener('change', function(e) {
            const selectedFiles = document.getElementById('selectedFiles');
            selectedFiles.innerHTML = '';

            if (this.files.length > 0) {
                Array.from(this.files).forEach(file => {
                    const fileSize = (file.size / (1024 * 1024)).toFixed(2);
                    const fileItem = document.createElement('div');
                    fileItem.className = 'bg-gray-100 px-3 py-1 rounded-lg flex items-center text-sm';
                    fileItem.innerHTML = `
                        <i class="fa fa-file-o mr-2 text-primary"></i>
                        <span class="truncate max-w-xs">${file.name}</span>
                        <span class="ml-2 text-gray-500">(${fileSize} MB)</span>
                        <button onclick="removeFile('${file.name}')" class="ml-2 text-gray-400 hover:text-danger">
                            <i class="fa fa-times"></i>
                        </button>
                    `;
                    selectedFiles.appendChild(fileItem);
                });
            } else {
                selectedFiles.innerHTML = '<p class="text-gray-400 text-sm">未选择文件</p>';
            }
        });

        // 移除文件
        function removeFile(fileName) {
            const fileInput = document.getElementById('fileInput');
            const dt = new DataTransfer();

            Array.from(fileInput.files).forEach(file => {
                if (file.name !== fileName) {
                    dt.items.add(file);
                }
            });

            fileInput.files = dt.files;

            // 更新文件列表显示
            const selectedFiles = document.getElementById('selectedFiles');
            selectedFiles.innerHTML = '';

            if (fileInput.files.length > 0) {
                Array.from(fileInput.files).forEach(file => {
                    const fileSize = (file.size / (1024 * 1024)).toFixed(2);
                    const fileItem = document.createElement('div');
                    fileItem.className = 'bg-gray-100 px-3 py-1 rounded-lg flex items-center text-sm';
                    fileItem.innerHTML = `
                        <i class="fa fa-file-o mr-2 text-primary"></i>
                        <span class="truncate max-w-xs">${file.name}</span>
                        <span class="ml-2 text-gray-500">(${fileSize} MB)</span>
                        <button onclick="removeFile('${file.name}')" class="ml-2 text-gray-400 hover:text-danger">
                            <i class="fa fa-times"></i>
                        </button>
                    `;
                    selectedFiles.appendChild(fileItem);
                });
            } else {
                selectedFiles.innerHTML = '<p class="text-gray-400 text-sm">未选择文件</p>';
            }
        }

        // 字符计数
        document.getElementById('userInput').addEventListener('input', function() {
            const charCount = this.value.length;
            document.getElementById('charCount').textContent = charCount;

            if (charCount > 500) {
                document.getElementById('charCount').classList.add('text-danger');
            } else {
                document.getElementById('charCount').classList.remove('text-danger');
            }
        });

        // 上传文件
        function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const files = fileInput.files;
            const uploadBtn = document.getElementById('uploadBtn');
            const uploadStatus = document.getElementById('uploadStatus');

            // 禁用按钮并显示加载状态
            uploadBtn.disabled = true;
            uploadBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>上传中...';
            uploadStatus.textContent = '';

            const formData = new FormData();

            // 添加所有选中的文件
            if (files.length > 0) {
                for (let i = 0; i < files.length; i++) {
                    formData.append('files', files[i]);
                }
            }

            fetch('http://localhost:5000/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'success') {
                    // 存储会话ID
                    localStorage.setItem('sessionId', data.session_id);

                    // 更新会话状态
                    const sessionStatus = document.getElementById('sessionStatus');
                    sessionStatus.innerHTML = `
                        <i class="fa fa-circle text-success mr-1"></i>
                        <span>已上传 ${data.files.length} 个文件</span>
                    `;

                    uploadStatus.innerHTML = `
                        <span class="text-success flex items-center">
                            <i class="fa fa-check-circle mr-1"></i>
                            上传成功，会话ID: ${data.session_id.substring(0, 8)}...
                        </span>
                    `;

                    // 启用生成按钮
                    document.getElementById('generateBtn').disabled = false;

                    // 显示成功消息
                    showToast('文件上传成功', 'success');
                } else {
                    uploadStatus.innerHTML = `
                        <span class="text-danger flex items-center">
                            <i class="fa fa-exclamation-circle mr-1"></i>
                            上传失败: ${data.message}
                        </span>
                    `;
                    showToast(`上传失败: ${data.message}`, 'error');
                }
            })
            .catch(error => {
                uploadStatus.innerHTML = `
                    <span class="text-danger flex items-center">
                        <i class="fa fa-exclamation-circle mr-1"></i>
                        上传错误: ${error.message}
                    </span>
                `;
                showToast(`上传错误: ${error.message}`, 'error');
            })
            .finally(() => {
                // 恢复按钮状态
                uploadBtn.disabled = false;
                uploadBtn.innerHTML = '<i class="fa fa-upload mr-2"></i>上传文件';
            });
        }

        // 生成内容
        function generateContent() {
            const userInput = document.getElementById('userInput').value.trim();
            const sessionId = localStorage.getItem('sessionId');
            const generateBtn = document.getElementById('generateBtn');
            const resultSection = document.getElementById('resultSection');
            const result = document.getElementById('result');

            if (!userInput) {
                showToast('请输入问题', 'warning');
                return;
            }

            // 显示加载中
            document.getElementById('loadingOverlay').classList.remove('hidden');
            document.getElementById('loadingText').textContent = '正在生成回答...';
            generateBtn.disabled = true;
            generateBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>生成中...';

            const data = {
                session_id: sessionId,
                input: userInput
            };

            fetch('http://localhost:5000/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(resultData => {
                // 隐藏加载中
                document.getElementById('loadingOverlay').classList.add('hidden');

                if (resultData.status === 'success') {
                    // 显示结果区域
                    resultSection.classList.remove('hidden');

                    // 格式化结果内容
                    let formattedContent = resultData.generated_content;

                    // 简单的HTML格式化
                    formattedContent = formattedContent
                        .replace(/\n/g, '<br>')
                        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                        .replace(/\*(.*?)\*/g, '<em>$1</em>')
                        .replace(/`(.*?)`/g, '<code class="bg-gray-100 px-1 rounded">$1</code>');

                    result.innerHTML = `
                        <div class="mb-4">
                            <h3 class="font-semibold text-lg mb-2">问题:</h3>
                            <p class="text-gray-700">${userInput}</p>
                        </div>
                        <div class="mb-4">
                            <h3 class="font-semibold text-lg mb-2">回答:</h3>
                            <div class="prose max-w-none">${formattedContent}</div>
                        </div>
                        <div class="text-xs text-gray-500 mt-4">
                            上下文长度: ${resultData.context_length} 个字符
                        </div>
                    `;

                    showToast('回答生成成功', 'success');
                } else {
                    resultSection.classList.remove('hidden');
                    result.innerHTML = `
                        <div class="bg-danger/10 border border-danger/30 rounded-lg p-4 text-danger">
                            <h3 class="font-semibold mb-2 flex items-center">
                                <i class="fa fa-exclamation-triangle mr-2"></i>
                                生成失败
                            </h3>
                            <p>${resultData.message}</p>
                        </div>
                    `;
                    showToast(`生成失败: ${resultData.message}`, 'error');
                }
            })
            .catch(error => {
                // 隐藏加载中
                document.getElementById('loadingOverlay').classList.add('hidden');

                resultSection.classList.remove('hidden');
                result.innerHTML = `
                    <div class="bg-danger/10 border border-danger/30 rounded-lg p-4 text-danger">
                        <h3 class="font-semibold mb-2 flex items-center">
                            <i class="fa fa-exclamation-triangle mr-2"></i>
                            请求错误
                        </h3>
                        <p>${error.message}</p>
                    </div>
                `;
                showToast(`请求错误: ${error.message}`, 'error');
            })
            .finally(() => {
                // 恢复按钮状态
                generateBtn.disabled = false;
                generateBtn.innerHTML = '<i class="fa fa-magic mr-2"></i>生成回答';
            });
        }

        // 清除结果
        function clearResult() {
            document.getElementById('resultSection').classList.add('hidden');
            document.getElementById('result').innerHTML = '';
            showToast('结果已清除', 'info');
        }

        // 清除会话
        document.getElementById('clearSessionBtn').addEventListener('click', function() {
            localStorage.removeItem('sessionId');
            document.getElementById('sessionStatus').innerHTML = `
                <i class="fa fa-circle-o text-gray-400 mr-1"></i>
                <span>未上传文件</span>
            `;
            document.getElementById('selectedFiles').innerHTML = '<p class="text-gray-400 text-sm">未选择文件</p>';
            document.getElementById('fileInput').value = '';
            document.getElementById('resultSection').classList.add('hidden');
            document.getElementById('result').innerHTML = '';
            document.getElementById('uploadStatus').textContent = '';
            document.getElementById('generateBtn').disabled = true;
            showToast('会话已清除', 'info');
        });

        // 显示提示消息
        function showToast(message, type = 'info') {
            // 创建toast元素
            const toast = document.createElement('div');
            toast.className = `fixed bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg transform transition-all duration-300 ease-in-out z-50 flex items-center`;

            // 设置不同类型的样式
            if (type === 'success') {
                toast.classList.add('bg-success', 'text-white');
                toast.innerHTML = `<i class="fa fa-check-circle mr-2"></i>${message}`;
            } else if (type === 'error') {
                toast.classList.add('bg-danger', 'text-white');
                toast.innerHTML = `<i class="fa fa-exclamation-circle mr-2"></i>${message}`;
            } else if (type === 'warning') {
                toast.classList.add('bg-warning', 'text-white');
                toast.innerHTML = `<i class="fa fa-exclamation-triangle mr-2"></i>${message}`;
            } else {
                toast.classList.add('bg-primary', 'text-white');
                toast.innerHTML = `<i class="fa fa-info-circle mr-2"></i>${message}`;
            }

            // 添加到页面
            document.body.appendChild(toast);

            // 动画效果
            setTimeout(() => {
                toast.classList.add('translate-y-0');
                toast.classList.remove('translate-y-10');
            }, 10);

            // 自动关闭
            setTimeout(() => {
                toast.classList.add('opacity-0');
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 300);
            }, 3000);
        }

        // 页面加载时检查会话状态
        window.addEventListener('load', function() {
            const sessionId = localStorage.getItem('sessionId');
            const generateBtn = document.getElementById('generateBtn');

            if (sessionId) {
                document.getElementById('sessionStatus').innerHTML = `
                    <i class="fa fa-circle text-success mr-1"></i>
                    <span>会话已加载</span>
                `;
                generateBtn.disabled = false;
            } else {
                generateBtn.disabled = true;
            }

            // 初始化文件选择区域
            document.getElementById('selectedFiles').innerHTML = '<p class="text-gray-400 text-sm">未选择文件</p>';
        });
    </script>
</body>
</html>